package com.jsn.baselibx.retrofit
import com.google.gson.GsonBuilder
import com.jsn.baselibx.BASE_API
import com.jsn.baselibx.utils.AppManager
import kotlinx.coroutines.flow.DEFAULT_CONCURRENCY
import okhttp3.Cache
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
import javax.xml.transform.OutputKeys

//Http连接超时

const val CONNECT_TIMEOUT = 2L

/**
 * Http 读取超时
 */
const val READ_TIMEOUT = 20L

/**
 * Http 写入超时
 */
const val WRITE_TIMEOUT = 20L

/**
 * 缓存大小
 */
const val CACHE_SIZE = 10 * 1024 * 1024L

class RetrofitApiFactory {

    companion object{

        @JvmStatic fun <T> createApi(serviceClass:Class<T>) : T {
            return  retrofit.create(serviceClass)
        }

        @JvmStatic fun <T> createApiBaseUrl(serviceClass:Class<T>, url:String) : T { //everytime we recreateRetrofit

            val retrofit=Retrofit.Builder()
                .baseUrl(url)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build()

            return  retrofit.create(serviceClass)
        }


        @JvmStatic val gson=GsonBuilder()
            .registerTypeAdapterFactory(NullStringToEmptyAdapterFactory<Any>()) //on a field which is null , reture "" .
            .serializeNulls()
            .setLenient()
            .setDateFormat("yyyy-MM-dd")
            .create()


        @JvmStatic val okHttpClient=OkHttpClient.Builder()
            .connectTimeout(CONNECT_TIMEOUT,TimeUnit.SECONDS)
            .readTimeout(READ_TIMEOUT,TimeUnit.SECONDS)
            .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
            .cache(Cache(AppManager.getApp().cacheDir, CACHE_SIZE))
            .addInterceptor(PrintIntercepter())
            .build()

        @JvmStatic val retrofit=Retrofit.Builder()
            .baseUrl(BASE_API)
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build()
    }
}